<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NInputNumber,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'

import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '提成明细' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '提成明细',
  initForm: {},
  doCreate: api.createPercentage,
  doUpdate: api.updatePercentage,
  doDelete: api.deletePercentage,
  refresh: () => $table.value?.handlerefresh(),
})

const roleOption = ref([])
const deptOption = ref([])
const timestamp = ref();

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value)
}

onMounted(() => {
  $table.value?.handleSearch()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 'auto',
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '生成时间',
    key: 'created_at',
    width: 'auto',
    align: 'center',
    ellipsis: {tooltip: true},
    fixed: 'left',
  },
  {
    title: '员工姓名',
    key: 'user_name',
    align: 'center',
    width:'auto',
    ellipsis: {tooltip: true},
  }, {
    title: '提成金额',
    key: 'price',
    align: 'center',
    width: 'auto',
    ellipsis: {tooltip: true},
  }, {
    title: '来源单号',
    key: 'order_id',
    align: 'center',
    width:'auto',
    ellipsis: {tooltip: true},
  }, {
    title: '客户姓名',
    key: 'receive_name',
    align: 'center',
    width:'auto',
    ellipsis: {tooltip: true},
  }, {
    title: '归属门店',
    key: 'space_name',
    align: 'center',
    width: 'auto',
    ellipsis: {tooltip: true},
  },
      {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/category/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => { },
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/category/delete']]
              ),
            default: () => h('div', {}, '确定删除该提成吗?'),
          }
        ),
      ]
    },
  },

]

</script>

<template>

      <CommonPage show-footer title="提成明细" style="padding: 0;margin: 0;">
        <!-- 表格 -->
        <CrudTable
            ref="$table"
            v-model:query-items="queryItems"
            :columns="columns"
            :get-data="api.getPercentage"
            :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="统计月份" :label-width="80">
              <n-date-picker
                v-model:value="timestamp"
                type="month"
                format="y年 M月"
                year-format="y年"
                month-format="M月"
                clearable
                @update:value="handleDateRangeChange"
              />
            </QueryBarItem>
            <QueryBarItem label="员工姓名" :label-width="80">
              <NInput
                  v-model:value="queryItems.name"
                  clearable
                  type="text"
                  placeholder="请输入员工姓名"
                  @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave">
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm" :validate-on-rule-change="true">
        <NFormItem label="业绩金额" path="price">
          <NInputNumber v-model:value="modalForm.price" :min="0" style="width: 100%;"/>
        </NFormItem>
      </NForm>
    </CrudModal>

      </CommonPage>

  <!-- 业务页面 -->
</template>
